<template>
  <div>
    <a-table
      :pagination="false"
      :columns="columns"
      :data-source="data"
      :row-key="(record) => record.code"
      :rowExpandable="(record) => record.isShowIcon"
      @expand="rowData"
      :expandedRowKeys="expandedRowKeys"
      class="components-table-demo-nested"
    >
      <template #bodyCell="{ column, record, text }">
        <!-- 文件名称 -->
        <!-- 文件类型 -->
        <!-- 保密等级 -->
        <!-- 是否文件模板 -->
        <!-- 文件负责人 -->
        <!-- 关键字 -->
        <!-- 主要内容 -->
        <!-- 申请原因 -->
        <!-- 删除项 -->
        <template v-if="column.key === 'operation'">
          <span @click="onUpload(record)" class="form-table-actions">导入文件</span>
          <span @click="onDelete(record.code)" class="form-table-actions">删除</span>
        </template>
      </template>
      <!-- 必填选项 -->
      <template #headerCell="{ column }"
        ><template v-if="column.key === 'name'"><span class="form-table-heard">文件名称</span></template>
        <template v-else-if="column.key === 'code'"><span class="form-table-heard">文件编码</span></template>
        <template v-else-if="column.key === 'directoryId'"><span class="form-table-heard">文件类型</span></template>
        <template v-else-if="column.key === 'version'"><span class="form-table-heard">版本号</span></template>
        <template v-else-if="column.key === 'securityLevel'"
          ><span class="form-table-heard">保密等级 </span>
          <a-tooltip placement="top" :overlayStyle="{ maxWidth: '655px' }">
            <template #title>
              <p>
                <span>1、绝密：指一旦泄密会使国家遭受严重危害和重大损失的。特指某些秘密文件资料，比如设计图纸、</span>
              </p>
              <p>
                <span>投标方案、电子帐本、程序源码、个人隐私以及一些包含重要信息的录像带和光盘等文件。</span>
              </p>
              <p>
                <span>2、机密：指标有“机密”密级的文件、简报等形式含有国家重要秘密、泄露会使国家的安全和利益</span>
              </p>
              <p>
                <span>遭受严重的损害的载体。有文件、简报、讲话材料，各种资料、报表、刊物，以文字、符号、图形、</span>
              </p>
              <p>
                <span>声、像等形式。</span>
              </p>
              <p>
                <span>3、秘密：可以称为私有文件，或者是因为某些原因，而不可以向大众公开的文件，如国家机密文件等。</span>
              </p>
              <p>
                <span>4、公开：没有什么影响，可以公开的。</span>
              </p>
            </template>
            <span class="promptIcon"><question-circle-outlined /></span>
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'isTemplate'"><span class="form-table-heard">是否文件模板</span></template>
        <template v-else-if="column.key === 'principalId'"><span class="form-table-heard">文件负责人</span></template>
        <template v-else-if="column.key === 'keyword'"><span class="form-table-heard">关键字</span></template>
        <template v-else-if="column.key === 'mainContent'"><span class="form-table-heard">主要内容</span></template>
        <template v-else-if="column.key === 'applyReason'"><span class="form-table-heard">申请原因</span></template>
      </template>

      <!-- 嵌套子表格插槽 -->
      <template #expandedRowRender>
        <a-table :columns="innerColumns" :data-source="innerData" :row-key="(record) => record.uploadTime" :pagination="false">
          <template #bodyCell="{ column, record, text, index }">
            <template v-if="column.dataIndex === 'remark' && index !== 0">
              <a-input v-if="text === '' || lineAdd" style="margin: -5px 0" v-model:value="valueRemark" @blur="inputValueRemark(valueRemark, record)" />
              <template v-else>
                {{ text }}
              </template>
            </template>
            <template v-if="column.key === 'operation' && index !== 0">
              <span v-if="data.length" @click="onDeleteDetail(record.uploadTime)" class="form-table-actions">删除</span>
            </template>
          </template>
        </a-table>
      </template>
    </a-table>
    <SelectChoose :tableItemConfig="getTableItemConfig" />
    <a-button type="dashed" @click="handleAdd" style="width: 100%">+ 添加</a-button>
    <!-- 导入文件 -->
  </div>
</template>

<script setup lang="ts">
import { ExclamationCircleOutlined, DownOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { onBeforeUnmount, defineComponent, ref, computed, createVNode, getCurrentInstance, UnwrapRef, reactive, watch, inject } from 'vue';
import { message, Modal } from 'ant-design-vue';
import SelectChoose from '../component/selectChoose.vue';
import { fileByName } from '@/config/api/documentApplication';
import { Api as ApiResource } from '@/config/api/resourceFileInfo';
import { DYNAMICLAYERUPLOAD, DYNAMICLOCALTABLE } from '@/mixins/subject/subject-types';
import { consumers } from 'stream';
import { keys } from 'xe-utils';

const showType = inject('showType').showType;
const getTableItemConfig = () => {
  return [
    {
      type: 'name',
      props: {},
      on: {
        recordName
      }
    },
    {
      type: 'directoryId',
      props: {},
      on: {
        recordType
      }
    },
    {
      type: 'securityLevel',
      props: {},
      on: {
        recordSecurityLevel
      }
    },
    {
      type: 'isTemplate',
      props: {},
      on: {
        recordIsTemplate
      }
    },
    {
      type: 'principalId',
      props: {},
      on: {
        recordPerson
      }
    },
    {
      type: 'keyword',
      props: {},
      on: {
        recordKeyword
      }
    },
    {
      type: 'mainContent',
      props: {},
      on: {
        recordMainContent
      }
    },
    {
      type: 'applyReason',
      props: {},
      on: {
        recordApplyReason
      }
    }
  ];
};

// 表格展开
const expandedRowKeys = ref([]);
const innerData: any = ref([]);
const rowData = (expanded, record) => {
  if (expanded) {
    // console.log(innerData.value.length);
    // if (innerData.value.length === 1) {
    //   innerData.value[0] = record;
    // }
    // if (innerData.value.length === 2) {
    //   innerData.value[1] = record;
    //   console.log('2', innerData.value);
    // }
    // innerData.value.push(record);
    // valueRemark.value = record.remark;
    // innerData.value[1] = record;
    valueRemark.value = record.remark;
  }

  // 只展开一行
  if (expandedRowKeys.value.length > 0) {
    let index = expandedRowKeys.value.indexOf(record.code);
    if (index > -1) {
      expandedRowKeys.value.splice(index, 1);
    } else {
      expandedRowKeys.value.splice(0, expandedRowKeys.value.length);
      expandedRowKeys.value.push(record.code);
    }
  } else {
    expandedRowKeys.value.push(record.code);
  }
};

const columns = [
  { title: '序号', dataIndex: 'index', key: 'index', width: 80, defaultSortOrder: 'descend', customRender: ({ index }) => index + 1 },
  { title: '文件名称', dataIndex: 'name', key: 'name', width: 120 },
  { title: '文件编码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '文件类型', dataIndex: 'directoryId', key: 'directoryId', width: 150 },
  { title: '版本号', dataIndex: 'version', key: 'version', width: 100 },
  { title: '保密等级', dataIndex: 'securityLevel', key: 'securityLevel', width: 140 },
  { title: '是否文件模板', dataIndex: 'isTemplate', key: 'isTemplate', width: 150 },
  { title: '文件负责人', dataIndex: 'principalId', key: 'principalId', width: 150 },
  { title: '关键字', dataIndex: 'keyword', key: 'keyword', width: 150 },
  { title: '主要内容', dataIndex: 'mainContent', key: 'mainContent', width: 150 },
  { title: '申请原因', dataIndex: 'applyReason', key: 'applyReason', width: 150 },
  { title: '操作', key: 'operation', width: 200 }
];

const data: any = ref([]);
let count = 1;
let lineAdd = ref(false);
const handleAdd = () => {
  count++;
  data.value.push({
    name: '',
    code: '',
    directoryId: '',
    version: '',
    securityLevel: '',
    isTemplate: '',
    principalId: '',
    keyword: '',
    mainContent: '',
    applyReason: '',
    attachmentFile: '',
    remark: '',
    size: '',
    uploadTime: '',
    isShowIcon: false
  });
  lineAdd.value = true;
  innerData.value = [];
};
function recordName(e, record) {
  // record.name = e;
  if (e.attachmentFile !== '') {
    e.isShowIcon = true;
  }
  Object.keys(record).forEach((key) => {
    record[key] = e[key];
  });
  innerData.value[0] = e;
}
function recordType(e, record) {
  record.directoryId = e;
}
function recordSecurityLevel(e, record) {
  record.securityLevel = e;
}
function recordIsTemplate(e, record) {
  record.isTemplate = e;
}
function recordPerson(e, record) {
  record.principalId = e;
}
function recordKeyword(e, record) {
  record.keyword = e;
}
function recordMainContent(e, record) {
  record.mainContent = e;
}
function recordApplyReason(e, record) {
  record.applyReason = e;
}
const valueRemark = ref<string>('');
function inputValueRemark(e, record) {
  record.remark = e;
  console.log('一行数据', record);
  console.log('子表格数据', innerData.value);
  console.log('总数据', data.value);
}
// 主表删除项
const onDelete = (code) => {
  Modal.confirm({
    title: '是否确定删除',
    autoFocusButton: null,
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    onOk() {
      data.value = data.value.filter((item) => item.code !== code);
    }
  });
};

// 文件详情删除项
const onDeleteDetail = (uploadTime) => {
  Modal.confirm({
    title: '是否确定删除',
    autoFocusButton: null,
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    onOk() {
      valueRemark.value = '';
      data.value.forEach((item) => {
        if (item.uploadTime === uploadTime) {
          item.isShowIcon = false;
          item.attachmentFile = '';
          item.remark = '';
          item.size = '';
          item.uploadTime = '';
        }
      });
      console.log('嵌套数据', innerData.value);
      console.log('总数据', data.value);
    }
  });
};
const innerColumns = [
  { title: '序号', dataIndex: 'index', key: 'index', width: 120, defaultSortOrder: 'descend', customRender: ({ index }) => index + 1 },
  { title: '文件', dataIndex: 'attachmentFile', key: 'attachmentFile', width: 120 },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 120 },
  { title: '大小', dataIndex: 'size', key: 'size', width: 120 },
  { title: '上传时间', dataIndex: 'uploadTime', key: 'uploadTime', width: 150 },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 120
  }
];

// 导入文件
// const rowExpandable = (record) => {
//   return record.isShowIcon;
// };
const { proxy }: any = getCurrentInstance();
const onUpload = (record) => {
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERUPLOAD,
    value: {
      state: {
        url: ApiResource.resourceUploadFile,
        downloadRule: '支持扩展名：.rar .zip .doc .docx .pdf .jpg...',
        callback: (data) => {
          data.isShowIcon = true;
          data.size = `${data.size / 1000}M`;
          data.attachmentFile = data.name;
          data.uploadTime = data.createdTime;
          innerData.value.push(data);
          (record.attachmentFile = data.name), (record.remark = ''), (record.size = `${data.size / 1000}M`), (record.uploadTime = data.createdTime);
          valueRemark.value = '';
          console.log('1', innerData.value);
        }
      }
    }
  });
};

onBeforeUnmount(() => {
  proxy.$NotificationPubSub.clearParams();
});
</script>
<style lang="less" scoped>
.form-table-heard:before {
  content: '*';
  color: #ff4d4f;
}
.form-table-actions {
  color: #005aea;
  cursor: pointer;
  margin-right: 10px;
}
.promptIcon {
  cursor: pointer;
  color: #005aea;
}
</style>
